var browserSync = require('browser-sync').create(),
  apiproxymiddleware = require('../middleware/api_proxy'),
  mockmiddleware = require('../middleware/mock'),
  webpack = require('webpack'),
  webpackMutiConfig = require('../utils/webpack-config'),
  querystring = require('querystring'),
  url = require('url'),
  pathToUrl = require('../utils/pathToUrl');

var html = require('./_html'),
  css = require('./_css'),
  watch = require('./_watch'),
  del = require('./_del');

// {命令名} --help  显示提示信息
exports.usage = '本地服务器  支持同步测试';
exports.set_options = function(optimist) {
  optimist.alias('p', 'port');
  optimist.describe('p', '服务端口号');
  optimist.alias('o', 'proxy');
  optimist.describe('o', '是否启用代理服务，默认端口是13180');
  optimist.alias('beta', 'beta环境');
  optimist.describe('beta', '处于beta环境，不开启webpack-hot-middleware功能');
  optimist.alias('r', 'reverse');
  return optimist.describe('r', '是否启用反向代理服务');
};

var setupServer = function(options) {
  var webpackConfig;
  if (options.o) {
    webpackConfig = webpackMutiConfig('beta');
  } else {
    webpackConfig = webpackMutiConfig('development');
  }

  var compiler = webpack(webpackConfig);

  browserSync.init({
    "server": {
      "baseDir": options.cwd,
      "middleware": [
        //接口转发
        function(req, res, next) {
          req.setEncoding('utf-8');
          res.setHeader("Access-Control-Allow-Origin", "*");
          res.setHeader(
            "Access-Control-Allow-Headers", "X-Requested-With");
          res.setHeader("Access-Control-Allow-Methods",
            "PUT, GET,POST,OPTIONS");

          next();
        },

        //接口转发
        function(req, res, next) {
          apiproxymiddleware.run(options, req, res, next);
        },
        //数据本地mock
        function(req, res, next) {
          mockmiddleware.run(options, req, res, next);
        },

        //热更新
        require('webpack-dev-middleware')(compiler, {
          stats: 'errors-only',
          //什么意思
          publicPath: pathToUrl('/', webpackConfig.output.publicPath)

        }),
        //数据本地mock
        function(req, res, next) {
          if (options.o) {
            next();
          } else {
            require('webpack-hot-middleware')(compiler);
            next();
          }

        }

      ]
    },
    "directory": true,
    "port": options.p || 80
  }, function() {
    console.log('本地服务器启动...');
    del(function() {
      html();
      css();
      watch();
    });
  });
};

exports.run = function(options) {
  setupServer(options);
};
